{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "93c65698",
   "metadata": {},
   "source": [
    "## 2.文件I/O\n",
    "\n",
    "**注意，在使用jupyter的时候，notebook文件必须和数据文件在同一文件夹下才可以打开**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a6ebc86a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1800  1  1    -6.1    -6.1    -6.1 1\r\n",
      "1800  1  2   -15.4   -15.4   -15.4 1\r\n",
      "1800  1  3   -15.0   -15.0   -15.0 1\r\n",
      "1800  1  4   -19.3   -19.3   -19.3 1\r\n",
      "1800  1  5   -16.8   -16.8   -16.8 1\r\n",
      "1800  1  6   -11.4   -11.4   -11.4 1\r\n",
      "1800  1  7    -7.6    -7.6    -7.6 1\r\n",
      "1800  1  8    -7.1    -7.1    -7.1 1\r\n",
      "1800  1  9   -10.1   -10.1   -10.1 1\r\n",
      "1800  1 10    -9.5    -9.5    -9.5 1\r\n"
     ]
    }
   ],
   "source": [
    "#读取文件\n",
    "!head stockholm_td_adj.dat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2cdb362",
   "metadata": {},
   "source": [
    "**读取文件到numpy建立的数组当中，可以使用genfromtext（generate）**\n",
    "\n",
    "shape得到数据文件的规模"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c04552d0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(77431, 7)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "data = np.genfromtxt('stockholm_td_adj.dat')\n",
    "data.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1464c43a",
   "metadata": {},
   "source": [
    "**存储和读取本地文件**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d1dfbfe4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.0818523 , 0.99373376, 0.0639095 ],\n",
       "       [0.17185521, 0.19336872, 0.58778146],\n",
       "       [0.51816981, 0.0588176 , 0.78873806]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "M = np.random.rand(3,3)\n",
    "#savetext会以文本文件形式保存\n",
    "np.savetxt(\"random-matrix.csv\", M, fmt='%.5f') #fmt确定数据格式\n",
    "\n",
    "np.save(\"random-matrix.npy\", M)#save默认是npy文件\n",
    "np.load(\"random-matrix.npy\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
